

/**
 * 求到n的斐波那契数
 * 1, 1, 2, 3, 5, 8, 13
 * 
 * f(1) = 1, f(2) = 1, f(3) = f(1) + f(2), f(n) = f(n - 1) + f(n - 2)
 * 
 * @param {*} n 
 */
const fib = (n) => {
    if (n < 0) return 0
    if (n === 1 || n === 2) return 1;

    // n必定大于2
    let sum = 0;
    let left = 1,
        right = 1;

    for (let i = 2; i < n; i++) {
        sum = left + right
        left = right;
        right = sum
    }
    return sum;
}

const fib2 = (n) => {
    if (n < 0) return 0
    if (n === 1 || n === 2) return 1;

    // n必定大于2
    let left = 1,
        right = 1;

    for (let i = 2; i < n; i++) {
        right = left + right;
        left = right - left;
    }
    return right;
}


console.log(fib2(5))

